package cn.itcast.xuesheng.web.servlet;

import cn.itcast.xuesheng.domain.User;
import cn.itcast.xuesheng.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String, String[]> parameterMap = req.getParameterMap();
        String checkCode = req.getParameter("checkCode");
        HttpSession httpSession =req.getSession();
        String checkcode_session = (String) req.getSession().getAttribute("checkcode_session");
//        httpSession.removeAttribute("checkcode_session");
        Map<String,Object> map=new HashMap<>();
        if (checkcode_session!=null&&checkcode_session.equalsIgnoreCase(checkCode)){
            User LoginUser =new User();
            try {
                BeanUtils.populate(LoginUser,parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            UserServiceImpl userService=new UserServiceImpl();
            User loginuser = userService.isLogin(LoginUser);
            if (loginuser == null){
                map.put("Tcheck",1);
                map.put("msg","用户名或密码出错");
            }
            else {
                map.put("Tcheck",2);
                map.put("msg","用户名密码正确");
                req.getSession().setAttribute("user",loginuser);
            }
        }
        else {
            map.put("Tcheck",0);
            map.put("msg","验证码出错");
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getWriter(),map);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(req, response);
    }
}
